package auth

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
	"go-vue3-ts-nativeUI-unocss/internal/services"
)

const (
	// API_URL 卡密验证接口地址
	API_URL = "https://env-00jxu65bfie3.dev-hz.cloudbasefunction.cn/http/router/admin/card/pub/verify"
	// PRODUCT_ID 产品ID
	PRODUCT_ID = "exe-batch-create-livingroom"
)

// LoginRequest 登录请求参数
type LoginRequest struct {
	LoginID  string `json:"loginId"`
	LoginKey string `json:"loginKey"`
}

// LoginResponse 登录响应
type LoginResponse struct {
	Code    int    `json:"code"`
	Result  bool   `json:"result"`
	Message string `json:"msg"`
}

// VIPVerifyRequest 卡密验证请求
type VIPVerifyRequest struct {
	Key         string `json:"key"`
	ProductID   string `json:"product_id"`
	ID          string `json:"id"`
	MachineCode string `json:"machineCode"`
}

// AuthService 认证服务
type AuthService struct {
	machineInfo *MachineInfo
	logService  *services.LogService
}

// NewAuthService 创建认证服务实例
func NewAuthService() *AuthService {
	return &AuthService{
		machineInfo: NewMachineInfo(),
		logService:  services.GetLogService(),
	}
}

// Login 登录验证
func (a *AuthService) Login(loginID, loginKey string) (*LoginResponse, error) {
	// 检查必要参数
	if loginID == "" || loginKey == "" {
		a.logService.Debug("auth", "登录参数为空", nil)
		return &LoginResponse{
			Code:    400,
			Result:  false,
			Message: "登录ID或密钥不能为空",
		}, nil
	}

	// 获取机器码
	machineCode := a.machineInfo.GetUUID()

	// 构建请求数据
	reqData := VIPVerifyRequest{
		Key:         loginKey,
		ProductID:   PRODUCT_ID,
		ID:          loginID,
		MachineCode: machineCode,
	}

	// 序列化请求数据
	jsonData, err := json.Marshal(reqData)
	if err != nil {
		return &LoginResponse{
			Code:    500,
			Result:  false,
			Message: fmt.Sprintf("请求数据序列化失败: %v", err),
		}, nil
	}

	// 创建 HTTP 请求
	req, err := http.NewRequest("POST", API_URL, bytes.NewBuffer(jsonData))
	if err != nil {
		return &LoginResponse{
			Code:    500,
			Result:  false,
			Message: fmt.Sprintf("创建请求失败: %v", err),
		}, nil
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")

	// 创建 HTTP 客户端
	client := &http.Client{
		Timeout: 30 * time.Second,
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		a.logService.Error("auth", "登录请求失败", map[string]interface{}{
			"error": err.Error(),
		})
		return &LoginResponse{
			Code:    500,
			Result:  false,
			Message: fmt.Sprintf("请求失败: %v", err),
		}, nil
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return &LoginResponse{
			Code:    500,
			Result:  false,
			Message: fmt.Sprintf("读取响应失败: %v", err),
		}, nil
	}

	// 解析响应
	var result LoginResponse
	if err := json.Unmarshal(body, &result); err != nil {
		return &LoginResponse{
			Code:    500,
			Result:  false,
			Message: fmt.Sprintf("解析响应失败: %v", err),
		}, nil
	}

	// 适配返回格式：code: 0 表示成功
	if result.Code == 0 {
		result.Result = true
		a.logService.Info("auth", "登录成功", map[string]interface{}{
			"loginId": loginID,
		})
	} else {
		result.Result = false
		if result.Message == "" {
			result.Message = "登录验证失败"
		}
		a.logService.Warn("auth", "登录失败", map[string]interface{}{
			"loginId": loginID,
			"message": result.Message,
			"code":    result.Code,
		})
	}

	return &result, nil
}
